import argparse
from db_util import *


def init_args():
    parser = argparse.ArgumentParser(prog='presto_etl_executor.py', description="""
            python3 presto_etl_load.py 
                    -t ads_fpos.sales_order

            ~~ have fun ~~
            """)

    parser.add_argument('-t', '--active_table', type=str, action='store', dest='active_table',
                        help=' 需要备份的表全名：ads_fpos.sales_order ')
    parser.add_argument('-k', '--max_key', type=str, action='store', dest='max_key',
                        help=' 判断最新的字断：pay_time ')

    args = parser.parse_args()
    return args


def load(args):
    if args.active_table:
        table = args.active_table.strip()
        get_active_table_sql = "SELECT active_table,max_value FROM etl_config.active_table WHERE table_name = '" + table + "' order by max_value desc limit 1"
        result = exec_presto_sql(get_active_table_sql)
        # 默认值
        check_result = ''
        active_table_name = args.active_table.strip() + '1'
        active_table_name1 = args.active_table.strip() + '1'
        active_table_name2 = args.active_table.strip() + '2'
        t_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        tp_str = time.strftime("%Y%m", time.localtime())

        try:
            check_result = exec_presto_sql("select * from " + table + " limit 1")
        except Exception as e:
            print("table " + table + " do not exsist ... ")
            return

        if check_result:
            if result:
                if result[0] == active_table_name1:
                    active_table_name = active_table_name2
                if result[0] == active_table_name2:
                    active_table_name = active_table_name1

            if args.max_key:
                mk = args.max_key.strip()
                max_sql = "select max(" + mk + ") from " + table
                mr = exec_presto_sql(max_sql)
                if mr and result and mr[0] == result[1]:
                    print(" already update .... ")
                    return
                else:
                    t_str = str(mr[0])

            exec_presto_sql("drop table if exists " + active_table_name)
            exec_presto_sql("create table " + active_table_name + " as select * from " + table)
            insert_sql = "insert into etl_config.active_table (table_name,active_table,max_value,p_date_str) values ('" \
                         + table + "','" \
                         + active_table_name + "','" \
                         + t_str + "','" \
                         + tp_str + "')"
            exec_presto_sql(insert_sql)

        else:
            print("do nothing ~~~")


def exec():
    args = init_args()
    load(args)


if __name__ == '__main__':
    exec()

